namespace SPI.AgentServer.Services.Tools;

public class GetTimeRangeTool : IQueryTool
{
    public string Name => "get_time_range";
    public string Description => "Get time range for natural language time descriptions";

    public Task<ToolResult> ExecuteAsync(Dictionary<string, object> parameters, CancellationToken cancellationToken = default)
    {
        if (!ValidateParameters(parameters, out var errors))
        {
            return Task.FromResult(new ToolResult
            {
                Success = false,
                Errors = errors
            });
        }

        var description = parameters["description"].ToString()!.ToLower();
        var now = DateTime.Now;
        DateTime startDate, endDate;

        try
        {
            switch (description)
            {
                case "today":
                case "今天":
                    startDate = now.Date;
                    endDate = now.Date.AddDays(1).AddSeconds(-1);
                    break;

                case "yesterday":
                case "昨天":
                    startDate = now.Date.AddDays(-1);
                    endDate = now.Date.AddSeconds(-1);
                    break;

                case "this week":
                case "本周":
                    startDate = now.Date.AddDays(-(int)now.DayOfWeek);
                    endDate = startDate.AddDays(7).AddSeconds(-1);
                    break;

                case "last week":
                case "上周":
                    startDate = now.Date.AddDays(-(int)now.DayOfWeek - 7);
                    endDate = startDate.AddDays(7).AddSeconds(-1);
                    break;

                case "this month":
                case "本月":
                    startDate = new DateTime(now.Year, now.Month, 1);
                    endDate = startDate.AddMonths(1).AddSeconds(-1);
                    break;

                case "last month":
                case "上个月":
                    startDate = new DateTime(now.Year, now.Month, 1).AddMonths(-1);
                    endDate = startDate.AddMonths(1).AddSeconds(-1);
                    break;

                case "this year":
                case "今年":
                    startDate = new DateTime(now.Year, 1, 1);
                    endDate = new DateTime(now.Year + 1, 1, 1).AddSeconds(-1);
                    break;

                case "last year":
                case "去年":
                    startDate = new DateTime(now.Year - 1, 1, 1);
                    endDate = new DateTime(now.Year, 1, 1).AddSeconds(-1);
                    break;

                default:
                    // Try to parse relative days
                    if (description.Contains("last") && description.Contains("days"))
                    {
                        var match = System.Text.RegularExpressions.Regex.Match(description, @"\d+");
                        if (match.Success && int.TryParse(match.Value, out var days))
                        {
                            startDate = now.Date.AddDays(-days);
                            endDate = now;
                        }
                        else
                        {
                            throw new ArgumentException($"Cannot parse time description: {description}");
                        }
                    }
                    else if (description.Contains("最近") && description.Contains("天"))
                    {
                        var match = System.Text.RegularExpressions.Regex.Match(description, @"\d+");
                        if (match.Success && int.TryParse(match.Value, out var days))
                        {
                            startDate = now.Date.AddDays(-days);
                            endDate = now;
                        }
                        else
                        {
                            throw new ArgumentException($"Cannot parse time description: {description}");
                        }
                    }
                    else
                    {
                        throw new ArgumentException($"Unknown time description: {description}");
                    }
                    break;
            }

            var result = new
            {
                startDate = startDate.ToString("yyyy-MM-dd HH:mm:ss"),
                endDate = endDate.ToString("yyyy-MM-dd HH:mm:ss"),
                startDateOnly = startDate.ToString("yyyy-MM-dd"),
                endDateOnly = endDate.ToString("yyyy-MM-dd"),
                description = description,
                days = (endDate - startDate).TotalDays
            };

            return Task.FromResult(new ToolResult
            {
                Success = true,
                Data = result
            });
        }
        catch (Exception ex)
        {
            return Task.FromResult(new ToolResult
            {
                Success = false,
                Errors = new List<string> { ex.Message }
            });
        }
    }

    public bool ValidateParameters(Dictionary<string, object> parameters, out List<string> errors)
    {
        errors = new List<string>();

        if (!parameters.ContainsKey("description") || string.IsNullOrWhiteSpace(parameters["description"]?.ToString()))
        {
            errors.Add("Parameter 'description' is required");
        }

        return errors.Count == 0;
    }
}
